//
//  BindCardTableVC.m
//  DaoZiJinFu
//
//  Created by woker on 16/7/13.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "BindCardTableVC.h"
#import "BindCardInputCell.h"
#import "BindCardBankCell.h"
#import "BindCardMsgCell.h"
#import "ChooseBank.h"
#import "BindCardFootView.h"
#import "ProtocolVC.h"
#import "targetconditionals.h"
#import "APNumberPad.h"
#define timeLine 30
#import "DZAddress.h"

#import "DZSqlManager.h"
@interface BindCardTableVC ()<BindCardInputCellDelegate,DZAddressDelegate,UITextFieldDelegate,APNumberPadDelegate>
{
    UITextField *nameStr;
    UITextField *idCardStr;
    UILabel *bankStr;
    UITextField *bankCardStr;
    UITextField *telStr;
    UITextField *msgStr;
  
    UIButton *receiveCodeBtn;
    
    BindCardFootView *footerView;
    NSString *bankName;
    NSString *bankID;
    NSString *bankLogo;
    NSString *pay_id;
    NSString *bankNumber;
    NSTimer *timer;
    NSInteger timerCount;
    
    UITextField *_bankNameTextFild;
    NSString *_provinces;
    
    DZAddress *DZaddress;
    NSString *dzProvince;
    NSString *dzCity;
    NSString *dzCityID;
    NSString *dzProvinceID;
    
    BOOL _isPhoneFlag;
    
    
    NSString *_userName;
    NSString *_idNumber;
    NSString *_bankNumber;
    NSString *_phoneNumber;
}

@end

@implementation BindCardTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTitleView:@"绑定银行卡"];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];
    [self.tableView registerNib:[UINib nibWithNibName:@"BindCardInputCell" bundle:nil] forCellReuseIdentifier:BINDCARDINPUTCELL];
    [self.tableView registerNib:[UINib nibWithNibName:@"BindCardBankCell" bundle:nil] forCellReuseIdentifier:BINDCARDBANKCELL];
    [self.tableView registerNib:[UINib nibWithNibName:@"BindCardMsgCell" bundle:nil] forCellReuseIdentifier:BINDCARDMSGCELL];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextBtnUseabled) name:@"textChangeNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveBankName:) name:@"returnBankName" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(agreeBtnSelect) name:@"agreeBtnSelectNotofication" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMsg) name:@"receiveMsgNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindCardOperation) name:@"nextBtnClickNotification" object:nil];
    timerCount = timeLine;
    if (self.editFlag) {
        [self getBindCardInformation];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)bindCardEnsureAction {
    DZRequestUtil *request =[[DZRequestUtil alloc] init];
    request.requestUrl = @"User/confirmBindBankCard";
    if (msgStr.text.length) {
      request.params = @{@"sms_code":msgStr.text};
    }
    //request.params = @{@"sms_code":@"999999"};
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        JSSHOW(model.msg);
        if (model.rt == 1) {
            JSSHOW(model.msg);
            [CommTools setUserInfo:response];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)getBindCardInformation {
    DZBankInfo *bank = [DZBankInfo mj_objectWithKeyValues:[DZUserInfo.userInfo.banks firstObject]];
    _userName = bank.card_name;
    _idNumber = bank.id_card;
    _bankNumber = bank.bank_card_number;
    _phoneNumber = bank.mobile;
    bankName = bank.bank_name;
    bankID = bank.bank_id;
    pay_id = bank.pay_id;
    bankLogo = bank.bank_logo_path;
    [self.tableView reloadData];
    [self nextBtnUseabled];
}




- (void)bindCardOperation {
    [self receiveMsg];
}

- (void)receiveMsg {
    if (nameStr.text.length == 0) {
        JSSHOW(@"持卡人未填写");
        return;
    }
    if (idCardStr.text.length == 0) {
        JSSHOW(@"身份证未填写");
        return;
    }
    if (bankStr.text.length == 0) {
        JSSHOW(@"未选择银行");
        return;
    }
    if (bankCardStr.text.length == 0) {
        JSSHOW(@"银行卡号未填写");
        return;
    }
    [self.view endEditing:YES];
    NSString *banksNumber = [_bankNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    DZprebindingBankCardRequest *request =[[DZprebindingBankCardRequest alloc] init];
    request.id_card = _idNumber;
    request.mobile  = _phoneNumber;
    request.card_name = _userName;
    request.bank_id = bankID;
    request.bank_name = bankName;
    request.bank_card_number = banksNumber;
    JSSHOWHUD;
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            JSSHOW(model.msg);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateAssetInformation" object:self];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)timeDown {
    timerCount --;
    [receiveCodeBtn setTitle:[NSString stringWithFormat:@"%lds",(long)timerCount] forState:UIControlStateNormal];
    if (timerCount == 0) {
        receiveCodeBtn.selected = NO;
        [receiveCodeBtn setTitle:@"获取" forState:UIControlStateNormal];
        timerCount = timeLine;
        [timer invalidate];
        timer = nil;
    }
}

- (void)receiveBankName:(NSNotification *)notifi {
    bankName = [[notifi userInfo] objectForKey:@"bankName"];
    bankID = [[notifi userInfo]objectForKey:@"bankID"];
    bankLogo = [[notifi userInfo]objectForKey:@"bankIcon"];
    bankStr.text = [[notifi userInfo] objectForKey:@"bankName"];
    pay_id = [[notifi userInfo] objectForKey:@"pay_id"];
    if ([pay_id integerValue] == 1) {
        _isPhoneFlag = YES;
    }else{
        _isPhoneFlag = NO;
    }
    [self.tableView reloadData];
    [self nextBtnUseabled];
}

- (void)nextBtnUseabled {
    if (nameStr.text.length && idCardStr.text.length && bankStr.text.length && bankCardStr.text.length && telStr.text.length && footerView.agreeBtn.selected == YES) {
        footerView.nextBtn.userInteractionEnabled = YES;
        footerView.nextBtn.backgroundColor = BLUE_COLOR;
    } else {
        footerView.nextBtn.userInteractionEnabled = NO;
        footerView.nextBtn.backgroundColor = UNUSEABLECOLOR;
    }
}

- (void)agreeBtnSelect {
    footerView.agreeBtn.selected = !footerView.agreeBtn.selected;
    if (footerView.agreeBtn.selected == YES) {
        [footerView.agreeBtn setImage:[UIImage imageNamed:@"选择"] forState:UIControlStateNormal];
    } else {
        [footerView.agreeBtn setImage:[UIImage imageNamed:@"未选择"] forState:UIControlStateNormal];
    }
    [self nextBtnUseabled];
}

- (void)readProtocol {
    ProtocolVC *protocol = [[ProtocolVC alloc] init];
    protocol.protocolType = 1;
    [self.navigationController pushViewController:protocol animated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!section) {
        return 2;
    } else {

        return 3;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 52;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (!section) {
        return 1;
    } else {
        return 124;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        footerView = [BindCardFootView loadView];
        footerView.agreeBtn.selected = YES;
        [footerView.protocolLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(readProtocol)]];
        return footerView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (!indexPath.section) {
        BindCardInputCell *inputCell = [BindCardInputCell cellWithTableView:tableView];
        inputCell.carema_button.hidden = YES;
        if (!indexPath.row) {
            inputCell.cellTitle.text = @"持卡人";
            inputCell.cellText.placeholder = @"请输入持卡人姓名";
            inputCell.cellText.keyboardType = UIKeyboardTypeDefault;
            inputCell.cellText.text = _userName;
            inputCell.cellText.delegate = self;
            nameStr = inputCell.cellText;
        } else {
            inputCell.carema_button.hidden = YES;
            inputCell.cellTitle.text = @"身份证号";
            inputCell.cellText.placeholder = @"请输入身份证号码";
            inputCell.cellText.delegate = self;
            inputCell.BindCardDelegate = self;
            inputCell.indexPath = indexPath;
            inputCell.cellText.text = _idNumber;
            idCardStr = inputCell.cellText;
            idCardStr.inputView = ({
                APNumberPad *numberPad = [APNumberPad numberPadWithDelegate:self];
                [numberPad.leftFunctionButton setTitle:@"X" forState:UIControlStateNormal];
                numberPad.leftFunctionButton.titleLabel.adjustsFontSizeToFitWidth = YES;
                numberPad;
            });
        }
        cell = inputCell;
    } else {
        if (!indexPath.row) {
            BindCardBankCell *bankCell = [BindCardBankCell cellWithTableView:tableView];
            bankCell.bankLabel.text = bankName;
            bankStr = bankCell.bankLabel;
            cell = bankCell;
        } else if (indexPath.row == 1) {
            BindCardInputCell *inputCell = [BindCardInputCell cellWithTableView:tableView];
            inputCell.cellTitle.text = @"银行卡号";
            inputCell.carema_button.hidden = YES;
            inputCell.cellText.placeholder = @"目前只支持储蓄卡";
            inputCell.BindCardDelegate = self;
            inputCell.indexPath = indexPath;
            inputCell.cellText.text = _bankNumber;
            inputCell.cellText.delegate = self;
            bankCardStr = inputCell.cellText;
            cell = inputCell;
        } else if (indexPath.row == 2) {
            BindCardInputCell *inputCell = [BindCardInputCell cellWithTableView:tableView];
            inputCell.cellTitle.text = @"预留手机号";
            inputCell.carema_button.hidden = YES;
            inputCell.cellText.placeholder = @"请输入银行预留手机号";
            inputCell.cellText.text = _phoneNumber;
            inputCell.cellText.delegate = self;
            telStr = inputCell.cellText;
            cell = inputCell;
        } else if (indexPath.row == 3) {
            BindCardMsgCell *msgCell = [BindCardMsgCell cellWithTableView:tableView];
            msgStr = msgCell.msgText;
            receiveCodeBtn = msgCell.msgButton;
            [receiveCodeBtn addTarget:self action:@selector(receiveMsg) forControlEvents:UIControlEventTouchUpInside];
            cell = msgCell;
        }
    }
    return cell;
}

- (void)numberPad:(APNumberPad *)numberPad functionButtonAction:(UIButton *)functionButton textInput:(UIResponder<UITextInput> *)textInput {
    [textInput insertText:@"X"];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == bankCardStr) {
        // 四位加一个空格
        if ([string isEqualToString:@""]) { // 删除字符
            if ((textField.text.length - 2) % 5 == 0) {
                textField.text = [textField.text substringToIndex:textField.text.length - 1];
            }
            return YES;
        } else {
            if (textField.text.length % 5 == 0) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        }
        return YES;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    _userName = nameStr.text;
    _idNumber = idCardStr.text;
    _bankNumber = bankCardStr.text;
    _phoneNumber = telStr.text;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    if (indexPath.section == 1 && indexPath.row == 0) {
        ChooseBank *chooseBank = [[ChooseBank alloc] init];
        [self.navigationController pushViewController:chooseBank animated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [timer invalidate];
    timer = nil;
    timerCount = timeLine;
    [receiveCodeBtn setTitle:@"获取" forState:UIControlStateNormal];
    receiveCodeBtn.userInteractionEnabled = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [JDHudUtil dismiss];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

@end
